package com.bw.controller;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bw.client.UserClient;
import com.bw.domain.BResult;
import com.bw.domain.ContractInfo;
import com.bw.domain.User;
import com.bw.service.ContractInfoService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import org.checkerframework.checker.units.qual.C;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
@RefreshScope
public class ContractController {

    @Autowired
    ContractInfoService contractInfoService;

    @Autowired
    UserClient userClient;

    @Autowired
    RedissonClient redissonClient;



    @RequestMapping("/flag")
    public Boolean flag(MultipartFile file) throws IOException, ServerException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        // Create a minioClient with the MinIO server playground, its access key and secret key.
        MinioClient minioClient =
                MinioClient.builder()
                        .endpoint("https://play.min.io")
                        .credentials("Q3AM3UQ867SPQQA43P2F", "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG")
                        .build();

        // Upload known sized input stream.
        minioClient.putObject(
                PutObjectArgs.builder().bucket("test-oo7").object("pic01").stream(
                                file.getInputStream(), file.getSize(), -1)
                        .contentType(file.getContentType())
                        .build());
        return true;
    }

    @RequestMapping("/list")
//    @Cacheable(value = "ContractList",key = "#pageNum",unless = "#pageNum!=1")
    public BResult list(ContractInfo query, @RequestParam(defaultValue = "1") Integer pageNum, HttpServletRequest request) {
        String token = request.getHeader("token"); //

        //0.判断用户有没有登录
        User user = userClient.selectUserByToken(token);

        if (user == null) {
            return BResult.error("请先登录！！");
        }
        //1. 分页
        PageHelper.startPage(pageNum, 3);
        // 把当前登录用户的Id 放到查询条件里
        query.setUserId(user.getId());

        List<ContractInfo> list = contractInfoService.listPage(query);
        PageInfo<ContractInfo> pageInfo = new PageInfo<>(list);

        return BResult.success(pageInfo);
    }


    @RequestMapping("/add")
    public BResult add(@Valid ContractInfo add, BindingResult result, HttpServletRequest request) {
        // 参数非法校验  非空验证
        if (result.hasErrors()){

            return BResult.error(result.getAllErrors().get(0).getDefaultMessage());

        }

        //0.判断是不是房东 验证当前登录人是否是房东
        User user = userClient.selectUserByToken(request.getHeader("token"));

        if (user == null) {
            return BResult.error("请先登录！！");
        }
        if (user.getRole() != 1) {
            return BResult.error("只有房东可以添加！！");
        }

        //防止重复提交功能
        String key = request.getRemoteAddr() + DigestUtil.md5Hex(JSONUtil.toJsonStr(add));
        // 尝试 往Redis里 存入一个键值对
        boolean b = redissonClient.getBucket(key).trySet(1);

        if (!b) { // 如果存入失败 ，说明之前已经有人添加过了， 重复了
            return BResult.error("不要重复提交！！");
        }

        //合同编号后端生成且不可编辑，规则:HT+随机数(雪花算法或UUID)
        String num = UUID.randomUUID().toString();
        add.setNum("HT" + num);
        // 签约时间
        add.setCreateTime(new Date());
        // 当前登录用户
        add.setUserId(user.getId());
        contractInfoService.save(add);

        return BResult.success("success");
    }
}